package game;

import net.message.MsgDispatcher;
import util.ConfPropertiesUtil;
import util.LogUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ClientManager {

    private static ClientManager instance = new ClientManager();

    public static ClientManager getInstance() {
        return instance;
    }

    private int threadPoolSize = 1;
    /**
     * 所有client都由id<>scene驱动
     */
    private Map<Integer, MsgDispatcher> scenes = new ConcurrentHashMap<>();
    /**
     * 所有要执行的行为
     */
    private Map<String, Class<?>> actionMap = new HashMap<>();

    private ClientManager() {

    }

    public void init(int threadPoolSize) {
        this.threadPoolSize = Math.max(threadPoolSize, this.threadPoolSize);
        for (int i = 0; i < this.threadPoolSize; i++) {
            MsgDispatcher scene = new MsgDispatcher();
            scenes.put(i, scene);
            scene.startUp();
        }
        //解析需要加载的行为
        actionMap.clear();
        String[] actionList = ConfPropertiesUtil.getInstance()._ACTION_LIST.split("\\|");
        for (String action : actionList) {
            if (action.trim().isEmpty()) {
                continue;
            }
            try {
                Class<?> classmate = Class.forName("game.action." + action);
                if (classmate == null) {
                    continue;
                }
                actionMap.put(action, classmate);
            } catch (ClassNotFoundException e) {
                LogUtil.game.error("Exception", e);
                continue;
            }
        }
    }

    public void addClient(Client client) {
        int sceneIndex = client.getIndex() % this.threadPoolSize;
        MsgDispatcher scene = scenes.get(sceneIndex);
        scene.addClient(client);
    }

    public void close() {
        scenes.forEach((k, v) -> {
            v.close();
        });
    }

    public Map<String, Class<?>> getActionMap() {
        return this.actionMap;
    }
}
